<html>
	<head>
		<title>The Real Franker!</title>
		<script type="text/javascript">
			var GOOGLE_API_KEY_DEFAULT    = "INSERT-YOUR-KEY";
			var MICROSOFT_API_KEY_DEFAULT = "INSERT-YOUR-KEY";
			var GOOGLE_URL_TEMPLATE = "https://www.googleapis.com/language/translate/v2?callback=translateCallBack&key=%APIKEY%&q=%TEXT%&target=%DST%&source=%SRC%";
			var MICROSOFT_URL_TEMPLATE = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=translateCallBack&contentType=text/plain&appId=%APIKEY%&text=%TEXT%&to=%DST%&from=%SRC%";
			var MICROSOFT_URL_LANGS_TEMPLATE = "http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguagesForTranslate?oncomplete=languagesCallBack&appId=%APIKEY%"
		</script>
		<script type="text/javascript">
			// broadcasts a message to all pages, used to propagate the settings (see issue #7)
			function broadcastMessage(name, payload) {
				for (var w = 0; w < safari.application.browserWindows.length; w++) {
					for (var t = 0; t < safari.application.browserWindows[w].tabs.length; t++) {
						safari.application.browserWindows[w].tabs[t].page.dispatchMessage(name, payload);
					}
				}
			}
			// sends a message to active page
			function sendMessage(name, payload) {
				safari.application.activeBrowserWindow.activeTab.page.dispatchMessage(name, payload);
			}
		</script>
		<script type="text/javascript">
			function translate(text) {
				var escapedText = encodeURIComponent(text).replace(/%22/g, '%26quot;');
				
				var langSrc = safari.extension.settings.lang_src;
				if (langSrc == "auto") {
					langSrc = "";
				}
				var langDst = safari.extension.settings.lang_dst;
				var engine = safari.extension.settings.engine;
				
				// handling "BING" as it was used before, in 1.2.2; this _additional_ check can be removed in version > 1.3.0
				if (engine == "BING") {
					engine = "MICROSOFT";
					safari.extension.settings.engine = "MICROSOFT";
				}
				
				var url = "";
				if (engine == "GOOGLE") {
					var apiKey = safari.extension.settings.google_api_key;
					if (!apiKey || apiKey == "") {
						alert("Franker error: Google Translate requires API key.\n\nPlease, set it at the Franker extension options page.");
						sendMessage("stop","");
						return;
					}
					url = GOOGLE_URL_TEMPLATE.replace("%APIKEY%", apiKey);
					url = url.replace("%TEXT%", escapedText);
					url = (langSrc != "") ? url.replace("%SRC%", langSrc) : url.replace("&source=%SRC%", "");
					url = url.replace("%DST%", langDst);
				} else if (engine == "MICROSOFT") {
					var apiKey = safari.extension.settings.microsoft_api_key;
					if (!apiKey || apiKey == "") {
						apiKey = MICROSOFT_API_KEY_DEFAULT;
					}
					if ((langSrc != "" && !(langSrc in microsoftLanguages)) || !(langDst in microsoftLanguages)) {
						alert("Franker error: Microsoft Translator does not support this language pair: "+langSrc+"-"+langDst+".\n\nSupported languages: "+microsoftLanguagesArray+".\n\nPlease, adjust language settings at the Franker extension options page.");
						sendMessage("stop","");
						return;
					}
					url = MICROSOFT_URL_TEMPLATE.replace("%APIKEY%", apiKey);
					url = url.replace("%TEXT%", escapedText);
					url = url.replace("%SRC%", langSrc);
					url = url.replace("%DST%", langDst);
				} else {
					return;
				}
				//alert(url);
				injectScript("frankerScript", url);
			}
			
			function translateCallBack(result) {
				var translation = "";
				var engine = safari.extension.settings.engine;
				if (engine == "GOOGLE") {
					translation = result.data.translations[0].translatedText;
				} else if (engine == "MICROSOFT") {
					translation = result;
				}
				sendMessage("frankateSelectionResponse", translation);
			}
			function respondToMessage(theMessageEvent) {
				switch (theMessageEvent.name) {
					case "frankateSelectionRequest":
						translate(theMessageEvent.message);
						break;
					
					// settings
					case "shortcutFrankateSelectionRequest":
						broadcastMessage("shortcutFrankateSelectionValue", safari.extension.settings.shortcut_frankate_selection);
						break;
					case "shortcutFrankateClearRequest":
						broadcastMessage("shortcutFrankateClearValue", safari.extension.settings.shortcut_frankate_clear);
						break;
					case "styleDestinationRequest":
						broadcastMessage("styleDestinationValue", safari.extension.settings.style_dst);
						break;
					case "injectBeforeRequest":
						broadcastMessage("injectBeforeValue", safari.extension.settings.inject_before);
						break;
					case "injectBracketsRequest":
						broadcastMessage("injectBracketsValue", safari.extension.settings.inject_brackets);
						break;

					// extra
					case "frankatePageRequest":
						var langSrc=safari.extension.settings.lang_src;
						if (langSrc == "auto") {
							langSrc = "" // means "detect language"
						}
						var langDst=safari.extension.settings.lang_dst;
						var activeTab = safari.application.activeBrowserWindow.activeTab;
						activeTab.url = 'http://translate.google.com/translate?u='+escape(activeTab.url)+'&hl='+langDst+'&ie=UTF-8&sl='+langSrc+'&tl='+langDst
						break;
					case "shortcutFrankatePageRequest":
						broadcastMessage("shortcutFrankatePageValue", safari.extension.settings.shortcut_frankate_page);
						break;
					case "statePageEnabledRequest":
						sendMessage("statePageEnabledValue", safari.extension.settings.state_frankate_page);
						break;
				}
			}
			function injectScript(id, url){
				var s = document.getElementById(id);
				if (s != null) {
					document.getElementsByTagName("head")[0].removeChild(s);
				}
				s = document.createElement("script");
				s.id = id;
				s.type = "text/javascript";
				s.src = url;
				document.getElementsByTagName("head")[0].appendChild(s);
			}
			safari.application.addEventListener("message", respondToMessage, false);
		</script>
		<!-- Context menu and toolbar buttons watcher -->
		<script type="text/javascript">
			function performCommand(event) {
				if (event.command === "frankate_selection") {
					sendMessage("frankateSelection", "");
				}
				if (event.command === "frankate_page") {
					sendMessage("frankatePage", "");
				}
			}
			safari.application.addEventListener("command", performCommand, false);
		</script>
		<!-- Settings change watcher -->
		<script>
			function settingsChanged(event) {
				switch (event.key) {
					case "shortcut_frankate_selection":
						broadcastMessage("shortcutFrankateSelectionValue", event.newValue + ":" + event.oldValue);
						break;
					case "shortcut_frankate_clear":
						broadcastMessage("shortcutFrankateClearValue", event.newValue + ":" + event.oldValue);
						break;
					case "shortcut_frankate_page":
						broadcastMessage("shortcutFrankatePageValue", event.newValue + ":" + event.oldValue);
						break;
				}
			}
			safari.extension.settings.addEventListener("change", settingsChanged, false);
		</script>
		<script type="text/javascript">
			var microsoftLanguages = {};
			var microsoftLanguagesArray = [];
			function languagesCallBack(result) {
				microsoftLanguagesArray = result;
				for(var i=0;i<result.length;i++) {
					microsoftLanguages[result[i]]='';
				}
			}
			injectScript("microsoftLanguagesScript", MICROSOFT_URL_LANGS_TEMPLATE.replace("%APIKEY%", MICROSOFT_API_KEY_DEFAULT));
		</script>
	</head>
	<body>
	</body>
</html>
